
(midi-start-server)

;; This should normally be in the user run control file.

(define m (midi-connect))

;; Print the connection information for 

(list (midi-client-host-name m)
      (midi-client-port-number m))	; => ("127.0.0.1" 57150)

;; Procedure to send note data.

(define (send-note note velocity duration)
  (midi-send m 0 #x90 note velocity)
  (schedule-delta duration
		  (lambda (time)
		    (midi-send m #x90 note 0))))

(send-note 65 100 0.1)

;; Play a chromatic scale, use a different program for each note.

(for-each (lambda (note program) 
	    (midi-send m 0 #xC0 program)
	    (send-note note 100 0.2) 
	    (thread-sleep! 0.2))
	  (iota 13 65)
	  (iota 13 1))

;; Play a random number of random diatonic notes of random duration
;; with random patches.

(let loop ((i (random-integer 25 50)))
  (if (> i 0)
      (let ((duration (random '(0.15 0.2 0.25 0.3))))
	(midi-send m #xC0 (random-integer 0 127))
	(send-note (random '(65 67 69 70 72 74 76 77)) 
		   (random-integer 6 127)
		   duration)
	(thread-sleep! duration)
	(loop (- i 1)))))

;; Print all incoming data

(midi-receiver-register 
 #t
 (lambda args (inform "Incoming:" args)))

;; Print all note on messages

(midi-receiver-register 
 (vector #x90 #x9F)
 (lambda (status note velocity) 
   (inform "Note on:" note velocity)))

;; Print all note on or note off messages at channel 0.

(midi-receiver-register 
 (list #x90 #x80) 
 (lambda (status note velocity) 
   (inform "Note on/off:" note velocity)))

;; Print all controller messages at channel 0.

(midi-receiver-register 
 #xB0 
 (lambda (status controller value) 
   (inform "Controller:" controller value)))

;; Delete all midi receivers.

(midi-receiver-clear)

;; Pass-Thru

(midi-receiver-register 
 #t (lambda args (apply midi-send m args)))

;; Shutdown engine.

(midi-disconnect m)

